/**
 * 提示方法
 * @param {String} 	title 提示文字
 * @param {String}  icon icon图片
 * @param {Number}  duration 提示时间
 */
export function toast(title = '提示', icon = 'none', duration = 1500) {
	return new Promise((resolve, reject) => {
		uni.showToast({
			title,
			icon,
			duration
		})
		setTimeout(()=>{
			resolve()
		}, duration)
	})

}

/**
 * 缓存操作
 */
export function setStorageSync(key, data) {
	return uni.setStorageSync(key, data)
}

export function getStorageSync(key) {
	return uni.getStorageSync(key)
}

export function removeStorageSync(key) {
	return uni.removeStorageSync(key)
}

export function clearStorageSync() {
	return uni.clearStorageSync()
}

/**
 * 页面跳转
 * @param {'navigateTo' | 'redirectTo' | 'reLaunch' | 'switchTab' | 'navigateBack' | number } url  转跳路径
 * @param {String} params 跳转时携带的参数
 * @param {String} type 转跳方式
 **/
export function useRouter(url, params = {}, type = 'navigateTo') {
	try {
		let queryStr = objToUrl(params);
		let newUrl = url;
		if (queryStr) {
			newUrl = `${url}?${queryStr}`
		}
		if (type === 'navigateBack') {
			uni[type]({
				delta: newUrl
			})
		} else {
			uni[type]({
				url: newUrl,
				fail: (err) => {
					if (err.errMsg.includes('fail can not navigateTo a tabbar page')) {
						useRouter(url, params, 'switchTab')
					}
					// console.log("err", err)
				}
			})
		}
	} catch (error) {
		console.error(error)
	}
}

export function objToUrl(obj) {
	let arr = [];
	for (let k in obj) {
		if (obj.hasOwnProperty(k)) {
			let str = JSON.stringify(obj[k])
			arr.push(encodeURIComponent(k) + '=' + encodeURIComponent(str))
		}
	}
	return arr.join('&')
}

export function toLoginPage(url = null) {
	clearStorageSync()
	// 将用户的目标路径保存下来
	// 这样可以实现 用户登录之后，直接跳转到目标页面
	if (url) {
		setStorageSync("afterLoginToPage", url);
	} else {
		const pages = getCurrentPages();
		let prePage = pages[pages.length - 1].route;
		// console.log("pages", pages)
		// console.log("pages[pages.length-1]", pages[pages.length-1])
		if (!prePage.includes('pages/login/index2')) {
			setStorageSync("afterLoginToPage", `/${prePage}`);
		}

	}
	useRouter('/pages/login/index2', null, 'reLaunch')
}


// 专门服务生成编号id
export function getRandomData() {
	let randomInt = Math.floor(Math.random() * (10000000 - 1 + 1)) + 1;
	return "SJ" + formatDate(new Date()) + randomInt;
}

function formatDate(date) {
	return (
		date.getFullYear() +
		padZero(date.getMonth() + 1) +
		padZero(date.getDate()) +
		padZero(date.getHours()) +
		padZero(date.getMinutes()) +
		padZero(date.getSeconds()) +
		padZero(date.getMilliseconds())
	);
}

function padZero(num) {
	return num < 10 ? '0' + num : num;
}